package com.wnm.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.wnm.dao.CartDao;
import com.wnm.dao.GoodsDao;
import com.wnm.pojo.Cart;
import com.wnm.pojo.Goods;
import com.wnm.service.CartService;
import com.wnm.util.DBUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private CartDao cartDao;
	@Autowired
	private GoodsDao goodsDao;

	@Override
	public void addCart(int userid, int goodsid, int nums) {
		Goods goods = goodsDao.findGoodsByGid(goodsid);
		BigDecimal salesprice = goods.getSalesprice();
		Cart cart = cartDao.findByUidAndGid(userid, goodsid);
		if (cart == null) {
			Cart _cart = new Cart();
			_cart.setGoodsid(goodsid);
			_cart.setNums(nums);
			_cart.setUserid(userid);
			BigDecimal price = salesprice.multiply(new BigDecimal(nums));
			_cart.setPrice(price);
			cartDao.add(_cart);
		} else {
			int _nums = cart.getNums() + nums;
			cart.setNums(_nums);
			cart.setPrice(salesprice.multiply(new BigDecimal(_nums)));
			cartDao.update(cart);
		}

	}

	@Override
	public List<Cart> findAllByUserid(int userid) {
		List<Cart> carts=cartDao.findAllByUserid(userid);
		
		return carts;
	}

	@Override
	public void delete(int userid, int goodsid) {
		cartDao.deleteByUeseidAndGoodsid(userid, goodsid);
	}

}
